package com.chatgpt.api.websocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class WebsocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 提取 GET 参数
        Map<String, String> params = extractParamsFromURL(request.getURI().getQuery());
        attributes.put("session_id", params.get("session_id"));
        attributes.put("chat_id", params.get("chat_id"));
        attributes.put("role_id", params.get("role_id"));
        attributes.put("model_id", params.get("model_id"));
        attributes.put("token", params.get("token"));
        log.info("{}", attributes);
        // TODO: 这里考虑是否需要做鉴权，验证 token
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }

    // 从 URL 链接中提取参数
    private Map<String, String> extractParamsFromURL(String url) {
        Map<String, String> map = new HashMap<>();
        String[] keyValues = url.split("&");
        for (String keyValue : keyValues) {
            String key = keyValue.substring(0, keyValue.indexOf("="));
            String value = keyValue.substring(keyValue.indexOf("=") + 1);
            map.put(key, value);
        }
        return map;
    }
}
